#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Simple sound effects generation script
Generate card play and end turn sound effects for the card game
Uses only built-in Python libraries
"""

import wave
import math
import os

def generate_card_play_sound():
    """Generate card play sound effect - crisp click sound"""
    sample_rate = 22050  # Lower sample rate for simplicity
    duration = 0.3  # 300ms
    
    frames = []
    
    for i in range(int(sample_rate * duration)):
        t = float(i) / sample_rate
        
        # Generate multiple frequency components
        freq1 = 800   # Main frequency
        freq2 = 1200  # Harmony
        freq3 = 600   # Bass support
        
        # Generate sine waves
        wave1 = math.sin(2 * math.pi * freq1 * t) * 0.4
        wave2 = math.sin(2 * math.pi * freq2 * t) * 0.3
        wave3 = math.sin(2 * math.pi * freq3 * t) * 0.2
        
        # Combine waves
        audio = wave1 + wave2 + wave3
        
        # Apply envelope (exponential decay)
        envelope = math.exp(-t * 8)
        audio = audio * envelope
        
        # Convert to 16-bit integer
        audio_int = int(audio * 16383)  # Scale to 16-bit range
        
        # Clamp to valid range
        if audio_int > 32767:
            audio_int = 32767
        elif audio_int < -32768:
            audio_int = -32768
            
        frames.append(audio_int)
    
    return frames, sample_rate

def generate_end_turn_sound():
    """Generate end turn sound effect - deep confirmation sound"""
    sample_rate = 22050
    duration = 0.5  # 500ms
    
    frames = []
    
    for i in range(int(sample_rate * duration)):
        t = float(i) / sample_rate
        
        # Lower frequency tones for deeper sound
        freq1 = 300   # Main frequency
        freq2 = 450   # Harmony
        freq3 = 200   # Bass
        
        # Generate sine waves
        wave1 = math.sin(2 * math.pi * freq1 * t) * 0.5
        wave2 = math.sin(2 * math.pi * freq2 * t) * 0.3
        wave3 = math.sin(2 * math.pi * freq3 * t) * 0.4
        
        # Combine waves
        audio = wave1 + wave2 + wave3
        
        # Apply envelope (slower decay)
        envelope = math.exp(-t * 3)
        audio = audio * envelope
        
        # Convert to 16-bit integer
        audio_int = int(audio * 20000)  # Scale to 16-bit range
        
        # Clamp to valid range
        if audio_int > 32767:
            audio_int = 32767
        elif audio_int < -32768:
            audio_int = -32768
            
        frames.append(audio_int)
    
    return frames, sample_rate

def save_wav_file(frames, sample_rate, filename):
    """Save audio frames as WAV file"""
    # Create directory if it doesn't exist
    dir_path = os.path.dirname(filename)
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
    
    # Open WAV file for writing
    wav_file = wave.open(filename, 'w')
    try:
        wav_file.setnchannels(1)  # Mono
        wav_file.setsampwidth(2)  # 16-bit
        wav_file.setframerate(sample_rate)
        
        # Convert frames to bytes
        for frame in frames:
            # Pack as signed 16-bit little-endian
            import struct
            wav_file.writeframes(struct.pack('<h', frame))
    finally:
        wav_file.close()
    
    print("Sound effect file generated: {}".format(filename))

def main():
    """Main function"""
    print("Generating game sound effects...")
    
    # Generate card play sound effect
    card_frames, card_rate = generate_card_play_sound()
    save_wav_file(card_frames, card_rate, "assets/audio/card_play.wav")
    
    # Generate end turn sound effect
    end_turn_frames, end_turn_rate = generate_end_turn_sound()
    save_wav_file(end_turn_frames, end_turn_rate, "assets/audio/end_turn.wav")
    
    print("All sound effect files generated successfully!")
    print("\nGenerated files:")
    print("  - assets/audio/card_play.wav (card play sound)")
    print("  - assets/audio/end_turn.wav (end turn sound)")

if __name__ == "__main__":
    main()